		var currentUsername = "";
		var currentUserIsAdmin;	
		var currentUserIsLoggedIn = false;
		var currentUserEmail = "";
		
		var welcomeMessageInterval;
		var ticketsArray;
		var currentButtonMode = "ViewAllTickets"; // All / My / Unassigned / Open / findSubmitterTickets / 
													// findSimilarTickets
		var currentlySelectedTicketID = -1; // will get updated when tickets are loaded
		var currentSortColumn = "ticketID"; // gets updated when sort by is changed
		
		function initialize()
		{			
			welcomeMessageInterval = setInterval(printWelcomeMessage, 100);
			getCurrentUsersEmail();
		}
		
		function renderEmailPage()
		{
			setBlockVisibility("ticketPage", "none");
			setBlockVisibility("singleTicketPage", "none");
			setBlockVisibility("ticketCreationPage", "none");
			setBlockVisibility("emailPage", "block");
			setBlockVisibility("changePasswordPage", "none");
			
			document.getElementById("emailPageAdminEmail").innerHTML = currentUserEmail;
			var currentlySelectedTicket = getCurrentlySelectedTicket();
			var currentlySelectedTicketSenderEmail = currentlySelectedTicket.senderEmail;
			document.getElementById("emailPageSenderEmail").innerHTML = currentlySelectedTicketSenderEmail;
			var subject = "Concerning ticket #" + currentlySelectedTicket.ticketID + ": '" + 
					currentlySelectedTicket.subject + "'";
			document.getElementById("emailPageEmailSubject").value = subject;
		}
		
		function sendEmail()
		{
			// alert("Time to send the email.");
			var adminEmail = currentUserEmail.replace("+", "-");
			var currentlySelectedTicket = getCurrentlySelectedTicket();
			var ticketSenderEmail = currentlySelectedTicket.senderEmail.replace("+", "-");
			var subject = document.getElementById("emailPageEmailSubject").value;
			var message = document.getElementById("emailPageEmailMessage").value;
			if(subject == "" || message == "")
			{
				alert("Please fill out the subject and message fields.")
			}
			else
			{
				// alert("Submitting email to server.");
				sendEmailThroughServer(adminEmail, ticketSenderEmail, subject, message);				
			}
		}
		
		function sendEmailThroughServer(sender, receiver, subject, message)
		{
			// alert("Sending Email to " + sender + " from " + receiver + " with subject '" + subject +
				// "' and message '" + message + "'");
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "sendEmail&sender=" + sender + "&receiver=" + receiver + 
					"&subject=" + subject + "&message=" + message;
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { sendEmailThroughServerListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function sendEmailThroughServerListener(httpRequest)
		{
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				console.log("Sending email through server : " + httpRequest.responseText);
				// document.getElementById("message").innerHTML += httpRequest.responseText;
				if(httpRequest.responseText.indexOf("error") > -1)
				{
					alert("There was a problem sending the email.");
				}
				else if(httpRequest.responseText.indexOf("success") > -1)
					/* TODO: render the tickets page once ticket is deleted */
					alert("The email was sent successfully.");
				else
				{
					alert("There was a problem sending the email.");
				}
			}
		}
		
		function singleTicketCloseTicket()
		{
			// alert("Time to close ticket");
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "closeTicket&ticketID=" + currentlySelectedTicketID;
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { singleTicketCloseTicketListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function singleTicketCloseTicketListener(httpRequest)
		{
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				console.log("Closing ticket with id#: " + currentlySelectedTicketID +
							":     " + httpRequest.responseText);
				// document.getElementById("message").innerHTML += httpRequest.responseText;
				if(httpRequest.responseText.indexOf("error") > -1)
				{
					alert("There was a problem closing the ticket.");
				}
				else if(httpRequest.responseText.indexOf("success") > -1)
				{
					/* TODO: render the tickets page once ticket is deleted */
					// alert("Successfully closed the ticket.")
				}
				else
				{
					alert("There was a problem closing the ticket.");
				}
				
				getTicketsFromServerDoNotCreateTicketsTable();
				setTimeout(function(){ updateSingleTicketPage(); }, 600);
			}
		}
		
		/* call after close / reopen ticket or assign / remove self button is clicked */
		function updateSingleTicketPage()
		{
			// alert("hello from updateSingleTicketPage()");
			// renderSingleTicketPage();
			var currentTicket = getCurrentlySelectedTicket();
			document.getElementById("currentlySelectedTicketStatus").innerHTML = currentTicket.status;
			document.getElementById("currentlySelectedTicketAdmin").innerHTML = currentTicket.admin;
			renderSingleTicketButtons();
		}
		
		function singleTicketReopenTicket()
		{
			// alert("Time to re-open ticket");
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "reopenTicket&ticketID=" + currentlySelectedTicketID;
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { singleTicketReopenTicketListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function singleTicketReopenTicketListener(httpRequest)
		{
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				console.log("Re-opening ticket with id#: " + currentlySelectedTicketID +
							":     " + httpRequest.responseText);
				// document.getElementById("message").innerHTML += httpRequest.responseText;
				if(httpRequest.responseText.indexOf("error") > -1)
				{
					alert("There was a problem re-opening the ticket.");
				}
				else if(httpRequest.responseText.indexOf("success") > -1)
				{
					/* TODO: render the tickets page once ticket is deleted */
					// alert("Successfully re-opened the ticket.");
				}
				else
				{
					alert("There was a problem re-opening the ticket.");
				}
				
				getTicketsFromServerDoNotCreateTicketsTable();
				setTimeout(function(){ updateSingleTicketPage(); }, 600);
			}
		}
		
		function singleTicketAssignSelf()
		{
			// alert("Time to assign self to ticket");
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "assignSelfToTicket&ticketID=" + currentlySelectedTicketID;
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { singleTicketAssignSelfListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function singleTicketAssignSelfListener(httpRequest)
		{
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				console.log("Assigning self to ticket with id#: " + currentlySelectedTicketID +
							":     " + httpRequest.responseText);
				// document.getElementById("message").innerHTML += httpRequest.responseText;
				if(httpRequest.responseText.indexOf("error") > -1)
				{
					alert("There was a problem assigning self to ticket.");
				}
				else if(httpRequest.responseText.indexOf("success") > -1)
				{
					/* TODO: render the tickets page once ticket is deleted */
					// alert("Successfully assigned self to ticket.");
				}
				else
				{
					alert("There was a problem assigning self to ticket.");
				}
				
				getTicketsFromServerDoNotCreateTicketsTable();
				setTimeout(function(){ updateSingleTicketPage(); }, 600);
			}
		}
		
		function singleTicketRemoveSelf()
		{
			// alert("Time to remove self from ticket");
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "removeSelfFromTicket&ticketID=" + currentlySelectedTicketID;
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { singleTicketRemoveSelfListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function singleTicketRemoveSelfListener(httpRequest)
		{
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				console.log("Removing self from ticket with id#: " + currentlySelectedTicketID +
							":     " + httpRequest.responseText);
				// document.getElementById("message").innerHTML += httpRequest.responseText;
				if(httpRequest.responseText.indexOf("error") > -1)
				{
					alert("There was a problem removing self from ticket.");
				}
				else if(httpRequest.responseText.indexOf("success") > -1)
				{
					/* TODO: render the tickets page once ticket is deleted */
					// alert("Successfully removed self from ticket.");
				}
				else
				{
					alert("There was a problem removing self from ticket.");
				}
				
				getTicketsFromServerDoNotCreateTicketsTable();
				setTimeout(function(){ updateSingleTicketPage(); }, 600);
			}
		}
		
		function singleTicketEmailUser()
		{
			// alert("Time to email user of ticket.");
			renderEmailPage();
		}
		
		function singleTicketDelete()
		{
			// alert("Time to delete ticket");
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "deleteTicket&ticketID=" + currentlySelectedTicketID;
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { singleTicketDeleteListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function singleTicketDeleteListener(httpRequest)
		{
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				console.log("Deleting ticket with id#: " + currentlySelectedTicketID +
							":     " + httpRequest.responseText);
				// document.getElementById("message").innerHTML += httpRequest.responseText;
				if(httpRequest.responseText.indexOf("error") > -1)
				{
					alert("There was a problem deleting the ticket.");
				}
				else if(httpRequest.responseText.indexOf("success") > -1)
					/* TODO: render the tickets page once ticket is deleted */
					alert("Successfully deleted ticket.");
				else
				{
					alert("There was a problem deleting the ticket.");
				}
				
				getTicketsFromServerAndCreateTicketsTable();
				// setTimeout(function(){ updateSingleTicketPage(); }, 600);
			}
		}
		
		function singleTicketFindSubmittersTickets()
		{
			// alert("Time to find this submitter's tickets by email");
			
			updateButtonMode("findSubmitterTickets");
		}
		
		function singleTicketFindSimilarTickets()
		{
			// alert("Time to find tickets with similar subjects");
			
			updateButtonMode("findSimilarTickets");
		}		
		
		function renderChangePasswordPage()
		{
			// alert("time to change the user's password");
			
			setBlockVisibility("ticketPage", "none");
			setBlockVisibility("singleTicketPage", "none");
			setBlockVisibility("ticketCreationPage", "none");
			setBlockVisibility("emailPage", "none");
			setBlockVisibility("changePasswordPage", "block");
		}
		
		function updateUserPassword()
		{
			var newPassword = document.getElementById("newPassword").value;
			if(newPassword == "")
			{
				alert("You must enter something for your password");
			}
			else
			{
				// alert("Updating password on server.");
				updateUserPasswordOnServer(newPassword);
			}
		}
		
		function updateUserPasswordOnServer(newPassword)
		{
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "updateUserPassword&newPassword=" + newPassword;
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { updateUserPasswordOnServerListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function updateUserPasswordOnServerListener(httpRequest)
		{
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				console.log("Password was changed? : ", httpRequest.responseText);
				// document.getElementById("message").innerHTML += httpRequest.responseText;
				if(httpRequest.responseText.indexOf("error") > -1)
				{					
					alert("There was some problem changing your password.");
				}
				else
				{
					alert("Your password has been changed.");
				}							
			}
		}
		
		function getCurrentUsersEmail()
		{
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "getUserEmail";
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { getCurrentUsersEmailListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function getCurrentUsersEmailListener(httpRequest)
		{
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				console.log("User email: ", httpRequest.responseText);
				// document.getElementById("message").innerHTML += httpRequest.responseText;
				if(httpRequest.responseText.indexOf("error") > -1)
				{
					currentUserEmail = "";
					alert("There was some problem getting the user's email.");
				}
				else
					currentUserEmail = httpRequest.responseText;				
			}
		}
		
		function renderTicketCreationPage()
		{
			setBlockVisibility("ticketCreationPage", "block");
			setBlockVisibility("ticketPage", "none");
			setBlockVisibility("singleTicketPage", "none");
			setBlockVisibility("emailPage", "none");
			setBlockVisibility("changePasswordPage", "none");
			
			document.getElementById("ticketCreationEmailAddress").innerHTML = currentUserEmail;
		}
		
		function submitNewTicket()
		{
			// alert("time to submit a new ticket");
			var firstName = document.getElementById("ticketCreationFirstName").value;
			var lastName = document.getElementById("ticketCreationLastName").value;
			var email = currentUserEmail;
			var subject = document.getElementById("ticketCreationSubject").value;
			var description = document.getElementById("ticketCreationDescription").value;
			if(firstName == "" || lastName == "" || email == "" || subject == "" || description == "")
			{
				alert("Please fill out all the fields before submitting the ticket.");
				return false;
			}
			else
			{
				submitNewTicketToServer(firstName, lastName, email, subject, description);
				// if(senderEmailThroughServer(firstName, lastName, email, subject, description))
					// alert("Successfully submitted ticket. You should received an email at " + email + "."):
				// else
					// alert("There was a problem submitting the ticket.");
			}
		}
		
		function submitNewTicketToServer(firstName, lastName, email, subject, description)
		{
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			email = email.replace("+", "-");
			var data = 'command=' + "submitNewTicket&senderFirstName=" + firstName + 
				"&senderLastName=" + lastName + "&senderEmail=" + email + "&subject=" + subject +
				"&description=" + description;
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = 
				function()
					{ submitNewTicketToServerListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function submitNewTicketToServerListener(httpRequest)
		{
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{				
				console.log("Response after submitting ticket: " + httpRequest.responseText);
				if(httpRequest.responseText == "error")
				{
					alert("There was some error submitting the ticket.");
				}
				else if(httpRequest.responseText.indexOf("success") > -1 )
					alert("The ticket was submitted successfully. You should get an email.");
				else
					alert("There was some error submitting the ticket.");				
			}
		}		
		
		function sortTickets()
		{
			// alert("Time to sort tickets");
			if(currentSortColumn == "ticketID")
				ticketsArray.sort(ticketIDcomparator);
				
			else if(currentSortColumn == "received")
				ticketsArray.sort(receivedComparator);
				
			else if(currentSortColumn == "senderName")
				ticketsArray.sort(senderNameComparator);
				
			else if(currentSortColumn == "senderEmail")
				ticketsArray.sort(senderEmailComparator);
				
			else if(currentSortColumn == "subject")
				ticketsArray.sort(subjectComparator);
				
			else if(currentSortColumn == "admin")
				ticketsArray.sort(adminComparator);
				
			else if(currentSortColumn == "status")
				ticketsArray.sort(statusComparator);
				
			else
				alert("Error sorting.");				
		}
		
		function sortTicketsFromButtonPress()
		{
			// alert("Time to sort tickets");
			if(currentSortColumn == "ticketID")
				ticketsArray.sort(ticketIDcomparator);
				
			else if(currentSortColumn == "received")
				ticketsArray.sort(receivedComparator);
				
			else if(currentSortColumn == "senderName")
				ticketsArray.sort(senderNameComparator);
				
			else if(currentSortColumn == "senderEmail")
				ticketsArray.sort(senderEmailComparator);
				
			else if(currentSortColumn == "subject")
				ticketsArray.sort(subjectComparator);
				
			else if(currentSortColumn == "admin")
				ticketsArray.sort(adminComparator);
				
			else if(currentSortColumn == "status")
				ticketsArray.sort(statusComparator);
				
			else
				alert("Error sorting.");
			renderTicketsPage();
		}
		
		function ticketIDcomparator(a, b)
		{
			if(a.ticketID > b.ticketID)
				return 1;
			else if(a.ticketID < b.ticketID)
				return -1;
			else
				return 0;
		}
		
		function receivedComparator(a, b)
		{
			if(a.received > b.received)
				return 1;
			else if(a.received < b.received)
				return -1;
			else
				return 0;
		}
		
		function senderNameComparator(a, b)
		{
			if(a.senderName > b.senderName)
				return 1;
			else if(a.senderName < b.senderName)
				return -1;
			else
				return 0;
		}
		
		function senderEmailComparator(a, b)
		{
			if(a.senderEmail > b.senderEmail)
				return 1;
			else if(a.senderEmail < b.senderEmail)
				return -1;
			else
				return 0;
		}
		
		function senderEmailComparator(a, b)
		{
			if(a.senderEmail > b.senderEmail)
				return 1;
			else if(a.senderEmail < b.senderEmail)
				return -1;
			else
				return 0;
		}
		
		function subjectComparator(a, b)
		{
			if(a.subject > b.subject)
				return 1;
			else if(a.subject < b.subject)
				return -1;
			else
				return 0;
		}
		
		function adminComparator(a, b)
		{
			if(a.admin > b.admin)
				return 1;
			else if(a.admin < b.admin)
				return -1;
			else
				return 0;
		}
		
		function statusComparator(a, b)
		{
			if(a.status > b.status)
				return 1;
			else if(a.status < b.status)
				return -1;
			else
				return 0;
		}
		
		function updateSortColumn(sortColumn)
		{
			currentSortColumn = sortColumn;
			// alert("sort column set to " + sortColumn);
		}
		
		function viewSelectedTicket()
		{
			getTicketsFromServerDoNotCreateTicketsTable(); // make sure we get any updates but
			// avoid changing the selected index so we know which ticket to display
			// alert("Time to view Selected ticket #" + currentlySelectedTicketID);
						
			renderSingleTicketPage();
		}
		
		function resetSingleTicketTable()
		{
			var singleTicketTable = document.getElementById("singleTicketTable");
			var length = singleTicketTable.rows.length;
			if(length == 1)
				return;
			else
			{
				/* Delete all rows but the header row */
				for(var i = 1; i < length; i++)
				{
					singleTicketTable.deleteRow(1); // this row is removed... so we delete second row as many
					// times as we have tickets to keep the sort row and the header row
				}
			}
		}
		
		function getCurrentlySelectedTicket()
		{
			var currentTicketID = currentlySelectedTicketID;
			for(var i = 0; i < ticketsArray.length; i++)
			{
				if(ticketsArray[i].ticketID == currentTicketID)
				{
					return ticketsArray[i];
				}
			}
		}
		
		function renderSingleTicketPage()
		{
			setBlockVisibility("ticketCreationPage", "none");
			setBlockVisibility("ticketPage", "none");
			setBlockVisibility("singleTicketPage", "block");
			setBlockVisibility("emailPage", "none");
			setBlockVisibility("changePasswordPage", "none");
			
			var ticketRows = document.getElementById("singleTicketTable")
			resetSingleTicketTable();
			var row;
			var cell;			
			
			
			renderSingleTicketButtons();
			var currentTicket = getCurrentlySelectedTicket();
			row = ticketRows.insertRow(); // add new rows at indexes after header row and sort row
			row.align = 'center';
			
			cell = row.insertCell(0);
			var txt = document.createTextNode(currentTicket.ticketID);
			cell.appendChild(txt);       // add its data (text)
			
			cell = row.insertCell(1);				
			txt = document.createTextNode(currentTicket.received);
			cell.appendChild(txt);
			
			cell = row.insertCell(2);				
			txt = document.createTextNode(currentTicket.senderName);
			cell.appendChild(txt);
			
			cell = row.insertCell(3);				
			txt = document.createTextNode(currentTicket.senderEmail);
			cell.appendChild(txt);
			
			cell = row.insertCell(4);				
			txt = document.createTextNode(currentTicket.subject);
			cell.appendChild(txt);
			
			cell = row.insertCell(5);
			cell.setAttribute('id', 'currentlySelectedTicketAdmin');			
			txt = document.createTextNode(currentTicket.admin);
			cell.appendChild(txt);
			
			cell = row.insertCell(6);
			cell.setAttribute('id', 'currentlySelectedTicketStatus');			
			txt = document.createTextNode(currentTicket.status);			
			cell.appendChild(txt);
			
			row = ticketRows.insertRow();
			row.align = 'center';
			cell = row.insertCell(0);
			var txt = document.createTextNode("Description");
			cell.appendChild(txt);
			cell = row.insertCell(1);
			cell.setAttribute('colspan', '6');
			var txt = document.createTextNode(currentTicket.description);
			cell.appendChild(txt); 
			/* Don't output radio button */
		}
		
		function renderSingleTicketButtons()
		{
			var currentTicket = getCurrentlySelectedTicket();
			if(currentTicket.status == "open")
			{
				setBlockVisibility("singleTicketCloseTicket", "inline");
				setBlockVisibility("singleTicketReopenTicket", "none");
			}
			else // if == "closed"
			{
				setBlockVisibility("singleTicketCloseTicket", "none");
				setBlockVisibility("singleTicketReopenTicket", "inline");
			}
			if(currentTicket.admin == "")
			{
				setBlockVisibility("singleTicketAssignSelf", "inline");
				setBlockVisibility("singleTicketRemoveSelf", "none");
			}
			else if(currentTicket.admin == currentUsername) // current admin user is assigned to ticket
			{
				setBlockVisibility("singleTicketAssignSelf", "none");
				setBlockVisibility("singleTicketRemoveSelf", "inline");
			}
			else // if admin is already assigned to ticket
			{
				setBlockVisibility("singleTicketAssignSelf", "none");
				setBlockVisibility("singleTicketRemoveSelf", "none");
			}
			
		}
		
		function updateButtonMode(buttonMode)
		{
			setBlockVisibility("ticketPage", "block");
			if(buttonMode == "ViewAllTickets")
			{
				document.getElementById("ViewAllTickets").style.display = "none"; // hide new mode
				if(!(currentButtonMode == "findSubmitterTickets" || currentButtonMode == "findSimilarTickets"))
					document.getElementById(currentButtonMode).style.display = "inline"; // bring back button for old mode
			}
			else if(buttonMode == "ViewAdminTickets")
			{
				document.getElementById("ViewAdminTickets").style.display = "none"; // hide new mode
				if(!(currentButtonMode == "findSubmitterTickets" || currentButtonMode == "findSimilarTickets"))
					document.getElementById(currentButtonMode).style.display = "inline"; // bring back button for old mode
			}
			else if(buttonMode == "ViewUnassignedTickets")
			{
				document.getElementById("ViewUnassignedTickets").style.display = "none"; // hide new mode
				if(!(currentButtonMode == "findSubmitterTickets" || currentButtonMode == "findSimilarTickets"))
					document.getElementById(currentButtonMode).style.display = "inline"; // bring back button for old mode
			}
			else if(buttonMode == "ViewOpenTickets")
			{
				document.getElementById("ViewOpenTickets").style.display = "none"; // hide new mode
				if(!(currentButtonMode == "findSubmitterTickets" || currentButtonMode == "findSimilarTickets"))
					document.getElementById(currentButtonMode).style.display = "inline"; // bring back button for old mode
			}
			else
			{
				// alert("We should be filtering by submitter's tickets or similar tickets (subject) " + 
						// " from single tickets page.");
				document.getElementById("ViewAllTickets").style.display = "inline";
				document.getElementById("ViewAdminTickets").style.display = "inline";
				document.getElementById("ViewUnassignedTickets").style.display = "inline";
				document.getElementById("ViewOpenTickets").style.display = "inline";
			}
			currentButtonMode = buttonMode;
			getTicketsFromServerAndCreateTicketsTable();						
			// renderTicketsPage();
		}
		
		function renderUserTicketsPage()
		{
			currentButtonMode = "ViewUserTickets";
			setBlockVisibility("adminViewTicketOptions", "none");
			getTicketsFromServerAndCreateTicketsTable(); // misnamed 
		}
		
		function getTicketsFromServerAndCreateTicketsTable()
		{
			if(!currentUserIsAdmin && currentButtonMode == "ViewAllTickets")
			{				
				alert("You are not an admin.");
				return;
			}
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			// TODO: finish updating with buttons / queries
			var data = 'command=' + "getAllTickets&buttonMode=" + currentButtonMode; // admin call that will be checked server side
			if(currentButtonMode == "findSubmitterTickets" || currentButtonMode == "findSimilarTickets")
				data += "&ticketID=" + currentlySelectedTicketID;
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { getTicketsFromServerAndCreateTicketsTableListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function getTicketsFromServerAndCreateTicketsTableListener(httpRequest)
		{	
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				// console.log("Getting ticket data: ", httpRequest.responseText);
				var rawTickets = httpRequest.responseText;
				console.log("Expecting tickets from server: " + httpRequest.responseText);
				if(httpRequest.responseText.indexOf("not admin") > -1)
				{
					/* Hide the admin page -- we shouldn't get here since admin page button is hidden
						if the user is not adn admin.*/
					alert("You are not an admin.");
				}
				else
				{
					// TODO: parse tickets into ticket objects / array
					parseTicketsAndSave(rawTickets);
					renderTicketsPage();
				}
			}
		}
		
		function getTicketsFromServerDoNotCreateTicketsTable()
		{
			if(!currentUserIsAdmin && currentButtonMode == "ViewAllTickets")
			{				
				alert("You are not an admin.");
				return;
			}
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			// TODO: finish updating with buttons / queries
			var data = 'command=' + "getAllTickets&buttonMode=" + currentButtonMode; // admin call that will be checked server side
			
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { getTicketsFromServerDoNotCreateTicketsTableListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function getTicketsFromServerDoNotCreateTicketsTableListener(httpRequest)
		{	
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				// console.log("Getting ticket data: ", httpRequest.responseText);
				var rawTickets = httpRequest.responseText;
				if(httpRequest.responseText == "not admin")
				{
					/* Hide the admin page -- we shouldn't get here since admin page button is hidden
						if the user is not adn admin.*/
					alert("You are not an admin.");
				}
				else
				{
					// TODO: parse tickets into ticket objects / array
					parseTicketsAndSave(rawTickets);
					// renderTicketsPage();
				}
			}
		}
		
		function resetAdminTable()
		{
			var adminTable = document.getElementById("adminTable");
			var length = adminTable.rows.length;
			if(length == 2)
				return;
			else
			{
				/* Delete all rows but the header row */
				for(var i = 2; i < length; i++)
				{
					adminTable.deleteRow(2); // this row is removed... so we delete row 3 as many
					// times as we have tickets to keep the sort row and the header row
				}
			}
			
		}
		
		function setSelectedTicket(ticketID)
		{
			currentlySelectedTicketID = ticketID;
			// alert("You selected ticket #" + ticketID);
		}
		
		function renderTicketsPage()
		{
			setBlockVisibility("ticketPage", "block");
			setBlockVisibility("singleTicketPage", "none");
			setBlockVisibility("ticketCreationPage", "none");
			setBlockVisibility("emailPage", "none");
			setBlockVisibility("changePasswordPage", "none");
			
			var ticketRows = document.getElementById("adminTable")
			resetAdminTable();
			var row;
			var cell;
			sortTickets();
			for(var i = 0; i < ticketsArray.length; i++)
			{
				row = ticketRows.insertRow(); // add new rows at indexes after header row and sort row
				row.align = 'center';
				
				cell = row.insertCell(0);
				var txt = document.createTextNode(ticketsArray[i].ticketID);
				cell.appendChild(txt);       // add its data (text)
				
				cell = row.insertCell(1);				
				txt = document.createTextNode(ticketsArray[i].received);
				cell.appendChild(txt);
				
				cell = row.insertCell(2);				
				txt = document.createTextNode(ticketsArray[i].senderName);
				cell.appendChild(txt);
				
				cell = row.insertCell(3);				
				txt = document.createTextNode(ticketsArray[i].senderEmail);
				cell.appendChild(txt);
				
				cell = row.insertCell(4);				
				txt = document.createTextNode(ticketsArray[i].subject);
				cell.appendChild(txt);
				
				cell = row.insertCell(5);				
				txt = document.createTextNode(ticketsArray[i].admin);
				cell.appendChild(txt);
				
				cell = row.insertCell(6);				
				txt = document.createTextNode(ticketsArray[i].status);
				cell.appendChild(txt);
				
				if(currentUserIsAdmin)
				{
					cell = row.insertCell(7);
					var rb = document.createElement('input');
					rb.setAttribute('type', 'radio');
					rb.setAttribute('name', 'selectedTicket');
					rb.setAttribute('value', ticketsArray[i].ticketID);
					// rb.onclick = viewTicket(ticketsArray[i].ticketID);
					rb.setAttribute('onclick', "setSelectedTicket(" + ticketsArray[i].ticketID + ");");
					// if(currentlySelectedTicketID == ticketsArray[i].ticketID)
					// {
						// rb.checked = true; /* maintains selected even after getting tickets again (if possible) */
						// currentlySelectedTicketID = ticketsArray[i].ticketID;
					// }
					// else 
					if(i == 0)
					{
						rb.checked = true;
						currentlySelectedTicketID = ticketsArray[i].ticketID;
					}
					cell.appendChild(rb);
				}
				else
				{
					cell = row.insertCell(7);
					txt = document.createTextNode("");
					cell.appendChild(txt);
				}
			}
		}
		
		function parseTicketsAndSave(rawTickets)
		{
			/* Take in the raw ticket data and use split() to extract it into ticket
			objects. */
			// rawTickets looks like:      ticket:ticket:ticket
			// each ticket looks like:     
			//		ticket#,received,sender name,sender email, subject, tech/admin,status
			
			rawTickets = rawTickets.split("|");
			ticketsArray = new Array(); // global
			ticket = new Array();
			for(var i = 0; i < rawTickets.length; i++)
			{
				ticket = rawTickets[i].split(",");
				ticketsArray[i] = new ticketObject(ticket[0], ticket[1], ticket[2], ticket[3],
									ticket[4], ticket[5], ticket[6], ticket[7]);
			}
			console.log("Newly retrieved Ticket data: ", ticketsArray);
			// console.log("Raw Ticket data: ", rawTickets);
		}
		
		function ticketObject(ticketID, received, senderName, senderEmail, subject, admin, status, description)
		{
			this.ticketID = parseInt(ticketID);
			this.received = received;
			this.senderName = senderName;
			this.senderEmail = senderEmail;
			this.subject = subject;
			this.admin = admin;
			this.status = status;
			this.description = description;
		}
		
		function logoutCurrentUser()
		{
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "logoutCurrentUser";
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { logoutCurrentUserListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function logoutCurrentUserListener(httpRequest)
		{
			window.location.replace("login.php");
		}
		
		function drawNavigationBar()
		{
			/* called by printWelcomeMessage() after we know if user is admin or not */
			/* Reveal the admin or user buttons depending on the user's privilege level */
			if(currentUserIsAdmin)			
				displayAdminNavBar();			
			else
				displayUserNavBar();
		}
		
		function displayAdminNavBar()
		{
			setBlockVisibility("adminNavBar", "block");
		}
		
		function displayUserNavBar()
		{
			setBlockVisibility("userNavBar", "block");
		}
		
		function toggleBlockVisibility(id)
		{
			var element = document.getElementById(id);		
			if(element.style.display == null || element.style.display == "")
			{
				element.style.display = "block";
			}
			if(element.style.display == "block")		
			{
				element.style.display = "none";
			}
			else
			{
				element.style.display = "block";
			}
		}
		
		function setBlockVisibility(id, displayType)
		{
			var element = document.getElementById(id);
			element.style.display = displayType;
		}
		
		function printWelcomeMessage()
		{			
			getCurrentUser();
			if(!currentUserIsLoggedIn)
			{
				return; // user is not logged in. We return. Other code will handle the redirect.
			}
			getIfCurrentUserIsAdmin();
			if(currentUsername == "" || currentUserIsAdmin == null)
			{			
				return;
			}
			else
			{
				document.getElementById("welcomeMessageToUser").innerHTML = "Welcome, " + currentUsername + ".";
				if(currentUserIsAdmin)
					document.getElementById("welcomeMessageToUser").innerHTML += " You are an admin.";
				else
					document.getElementById("welcomeMessageToUser").innerHTML += 
						" You are not an admin.";			
				clearInterval(welcomeMessageInterval);
				drawNavigationBar();
			}
			
		}
		
		function getIfCurrentUserIsAdmin()
		{
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "isUserAdmin";
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { getIfCurrentUserIsAdminListener(httpRequest); };
			httpRequest.send(data);
		}		
		
		function getIfCurrentUserIsAdminListener(httpRequest)
		{			
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				console.log("Is user admin: ", httpRequest.responseText);
				// document.getElementById("message").innerHTML += httpRequest.responseText;
				if(httpRequest.responseText == "true")
					currentUserIsAdmin = true;
				else
					currentUserIsAdmin = false;				
			}
		}
		
		function getCurrentUser()
		{
			var httpRequest = new XMLHttpRequest();
			if (!httpRequest) 
			{
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			var data = 'command=' + "whoIsLoggedIn";
			httpRequest.open('POST', 'global_ajax.php', true);
			httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			httpRequest.onreadystatechange = function() { getCurrentUserListener(httpRequest); };
			httpRequest.send(data);
		}
		
		function getCurrentUserListener(httpRequest)
		{
			if(httpRequest.readyState == 4 && httpRequest.status == 200)
			{
				console.log("Currently logged in user is: ", httpRequest.responseText);
				// document.getElementById("message").innerHTML += httpRequest.responseText;
				currentUsername = httpRequest.responseText;
				if(currentUsername == "")
					logoutCurrentUser();
				else
					currentUserIsLoggedIn = true;
			}
		}